﻿using ReaderDemo;
using RFIDLIB;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.ServiceModel;
using System.Threading;
using System.Windows.Forms;
using WindowsFormsApp.Services;

namespace WindowsFormsApp
{
    public partial class MainForm : Form
    {

        private bool Reading = false;
        private List<string> epcList = new List<string>();

        private int opType = 0;//连接类型 0为网口，1为USB口，2为串口
        //private HFReaderHelper HFReader;
        private bool isReadBlock = false;
        private Thread thread = null;
        private bool isCoiledRead = false;
        private System.Threading.Timer timer = null;

        /// <summary>
        /// 通过托盘菜单关闭程序标记
        /// </summary>
        bool formClose = false;


        /// <summary>
        /// Http service.
        /// </summary>
        private HttpService _http;

        public MainForm()
        {
            InitializeComponent();

            /**
             * enable the start button and disable the close button.
             */
            this.StartButton.Enabled = true;
            this.CloseButton.Enabled = false;
        }

        /// <summary>
        /// start the http server.
        /// </summary>
        private async void StartButton_Click(object sender, EventArgs e)
        {
            /**
             * start.
             */
            try
            {
                var port = Convert.ToInt32(this.PortNum.Value);
                bool ret = false;
                //连接
                if (Program.HFReader == null)
                {
                    Program.HFReader = new HFReaderHelper(RFIDCallBack);
                }

                //ret = HFReader.InitRFIDConn(opType, this.typeBox.Text, this.Com_cb.Text, this.Rate_tb.Text, this.OpFrame_tb.Text, IP_tb.Text, Port_tb.Text);
                ret = Program.HFReader.InitRFIDConn(this.comboBox1.Text);
                if (ret)
                {
                    MessageBox.Show("串口连接成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("串口连接失败,请检查设置连接情况!", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                }


                /**
                 * initialize http service.
                 */
                _http = new HttpService(port);

                await _http.StartHttpServer();

                MessageBox.Show("服务启动成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                /**
                 * disable the start button and enable the close button.
                 */
                this.StartButton.Enabled = false;
                this.PortNum.Enabled     = false;
                this.CloseButton.Enabled = true;
            }
            catch (AggregateException exception)
            {
                /**
                 * PLZ "Run as administrator".
                 */
                if (exception.Flatten().InnerExceptions.Any(ex => ex is AddressAccessDeniedException))
                {
                    MessageBox.Show("Permission denied.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show($"{exception.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #region 高频读写器UID接收方法
        private void RFIDCallBack(string UID)
        {
            if (!Reading)
            {
                return;
            }

            this.Invoke(new MethodInvoker(delegate
            {
                if (!epcList.Contains(UID))
                {
                    epcList.Add(UID);
                    //HFReader.stopReading();
                    //Thread.Sleep(500);
                    //string data = HFReader.TryReadRFTag(UID);
                    //if (data != null)
                    //{
                    //    this.return_tb.Text += "\r\n" +  DateTime.Now.ToString("HH:mm:ss:fff") + "\r\n" + "标签:" + UID + data;
                    //}
                    //else 
                    //{
           
                    //}
                    //HFReader.startReading();
                }
            }));
        }

        #endregion


        /// <summary>
        /// close the http server.
        /// </summary>
        private async void CloseButton_Click(object sender, EventArgs e)
        {
            /**
             * close.
             */
            try
            {
                //退出
                Program.HFReader.Dis_pose();
                await _http.CloseHttpServer();
                _http.Dispose();

                MessageBox.Show("Closed successfully!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                /**
                 * disable the start button and enable the close button.
                 */
                this.StartButton.Enabled = true;
                this.PortNum.Enabled     = true;
                this.CloseButton.Enabled = false;

            }
            catch (Exception exception)
            {
                MessageBox.Show($"{exception.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void MainForm_Resize(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
                notifyIcon1.Visible = true;
            }
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (WindowState == FormWindowState.Minimized)
                {
                    WindowState = FormWindowState.Normal;
                    this.Activate();//激活窗口
                    this.ShowInTaskbar = true;//托盘中显示
                    notifyIcon1.Visible = false;
                }
            }
        }

 
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
        

            #region 获取设备类型
            if (rfidlib_reader.RDR_LoadReaderDrivers("\\Drivers") != 0)
            {
                MessageBox.Show("驱动路径错误！！");
            }
            #endregion
            #region 获得串口
            string[] ArryPort = SerialPort.GetPortNames();
            this.comboBox1.Items.Clear();
            for (int i = 0; i < ArryPort.Length; i++)
            {
                comboBox1.Items.Add(ArryPort[i]);
            }
            if (comboBox1.Items.Count > 0)
            {
                comboBox1.SelectedIndex = 0;
            }
            #endregion
        
       }
    }
}
